﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Drawing;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_LinkBillController : MvcControllerBase
    {
        private LinkBillBLL bll = new LinkBillBLL();
        private static HttpFileCollection hfc;

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }


        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Detail()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.LinkCode).ToString());
            return View();
        }
        #endregion
        #region 查询数据

        #region 单据状态树
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "单据状态树", "GetList")]
        private List<TreeStatusEntity> GetList(string queryJson)
        {
            DataTable dt = bll.GetCountList(queryJson);
            List<TreeStatusEntity> li = new List<TreeStatusEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "all")
                        li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(LStateEnum.All), LStateEnum.All.ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unhanding")
                        li.Add(new TreeStatusEntity(LStateEnum.All.ToString(), EnumAttribute.GetDescription(LStateEnum.UnHanding), ((int)LStateEnum.UnHanding).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "handing")
                        li.Add(new TreeStatusEntity(LStateEnum.All.ToString(), EnumAttribute.GetDescription(LStateEnum.Handing), ((int)LStateEnum.Handing).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "completed")
                        li.Add(new TreeStatusEntity(LStateEnum.All.ToString(), EnumAttribute.GetDescription(LStateEnum.Completed), ((int)LStateEnum.Completed).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unreturnback")
                        li.Add(new TreeStatusEntity(((int)LStateEnum.Completed).ToString(), EnumAttribute.GetDescription(LStateEnum.UnReturnBack), ((int)LStateEnum.UnReturnBack).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "repaired")
                        li.Add(new TreeStatusEntity(((int)LStateEnum.Completed).ToString(), EnumAttribute.GetDescription(LStateEnum.Repaired), ((int)LStateEnum.Repaired).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "returnbill")
                        li.Add(new TreeStatusEntity(LStateEnum.All.ToString(), EnumAttribute.GetDescription(LStateEnum.ReturnBill), ((int)LStateEnum.ReturnBill).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "cancelbill")
                        li.Add(new TreeStatusEntity(LStateEnum.All.ToString(), EnumAttribute.GetDescription(LStateEnum.CancelBill), ((int)LStateEnum.CancelBill).ToString(), dt.Rows[0][i].ToInt()));
                    else
                        continue;
                }
            }
            return li;
        }

        /// <summary>
        /// 获取单据状态树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取单据状态树", "GetStateTreeList")]
        public ActionResult GetStateTreeList(string queryJson)
        {
            var data = GetList(queryJson);
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "<" + item.Count + ">";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        #endregion

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取列表数据", "GetPageListJson")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            var data = bll.GetPageList(pagination, queryJson);
            //if (!OperatorProvider.Provider.Current().IsSystem)
            //{
            //   data = data.Where(t => t.CreateUserId == OperatorProvider.Provider.Current().UserId);
            //}
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取实体", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = bll.GetEntity(keyValue);
            var file = new AttachFileBLL().GetList(keyValue);
            var jsonData = new
            {
                data1 = data,
                data3 = file
            };
            return Content(jsonData.ToJson());

        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取联系单转单的单据", "GetBills")]
        public ActionResult GetBills(string SourceId)
        {
            StringBuilder sHtml = new StringBuilder();
            string strHTML = string.Empty;
            int count = 0; string state = "";
            var repairdata = new RepaireBLL().GetList().Where(t => t.SourceId == SourceId).ToList();
            var complaintdata = new ComplaintsBLL().GetList().Where(t => t.SourceId == SourceId).ToList();

            #region 维修单
            if (repairdata != null && repairdata.Count() > 0)
            {
                count = count + repairdata.Count();
                for (int i = 0; i < repairdata.Count(); i++)
                {
                    switch (repairdata[i].State)
                    {
                        case 1: state = "<span style=' position: relative; float: left;margin-left:10px;'class=\"label label-success\">未派单</span>"; break;
                        case 2: state = "<span style=' position: relative; float: left;margin-left:10px;'class=\"label label-danger\">派单中</span>"; break;
                        case 3: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-success\">待修中</span>"; break;
                        case 4: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">进行中</span>"; break;
                        case 5: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-success\">待回访/检验</span>"; break;
                        case 6: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">已完成</span>"; break;
                        case 7: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-success\">已退单</span>"; break;
                        case 8: state = "<span style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">已取消</span>"; break;
                        default: state = ""; break;
                    }
                    strHTML += "<div style='position: relative; float: left; border: 1px solid #dcd6d6; width: 250px; height: 100px; margin: 5px; padding: 10px; box-shadow: 5px 5px 10px #dcd6d6; '> <ul>";
                    strHTML += "<li style='position: relative; float: left; width: 220px; height: 20px; text-align: center;'><span style=' position: relative; float: left;'>维修单</span><span style=' float: right; right: 0px;'>" + repairdata[i].Code + "</span></li>";
                    strHTML += "<li style=' position: relative; float: left; width: 220px; height: 20px; text-align: center;'></li><li style='position: relative; float: left; width: 220px; height: 20px; text-align: center;'>" + state;
                    string tmpStr = string.Format("<input style=' float: right; right: 0px; margin-right: 10px; cursor: pointer;' type='button' id={0} class='btn-primary btn-mini' value='查看详情'  onclick=\"OnView('{0}',1)\" />", repairdata[i].Id);
                    strHTML += tmpStr;
                    strHTML += "</li></ul></div>";
                }
            }
            #endregion
            #region 投诉单
            if (complaintdata != null && complaintdata.Count() > 0)
            {
                count = count + complaintdata.Count();
                for (int j = 0; j < complaintdata.Count(); j++)
                {
                    switch (complaintdata[j].State)
                    {
                        case 1: state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-success\">未处理</span>"; break;
                        case 2: state = "<span  style=' position: relative; float: left;margin-left:10px;'  class=\"label label-success\">未派单</span>"; break;
                        case 3: state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">派单中</span>"; break;
                        case 4: state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">处理中</span>"; break;
                        case 5:
                            if (complaintdata[j].ReturnBackMark == 0) state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-primary\">已处理，未回访</span>";
                            else state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-primary\">已处理，已回访</span>"; break;
                        case 6: state = "<span  style=' position: relative; float: left;margin-left:10px;' class=\"label label-danger\">不处理</span>"; break;
                        default: state = ""; break;
                    }
                    strHTML += "<div style='position: relative; float: left; border: 1px solid #dcd6d6; width: 250px; height: 100px; margin: 5px; padding: 10px; box-shadow: 5px 5px 10px #dcd6d6; '> <ul>";
                    strHTML += "<li style='position: relative; float: left; width: 220px; height: 20px; text-align: center;'><span style=' position: relative; float: left;'>投诉单</span><span style=' float: right; right: 0px;'>" + complaintdata[j].Code + "</span></li>";
                    strHTML += "<li style=' position: relative; float: left; width: 220px; height: 20px; text-align: center;'></li><li style='position: relative; float: left; width: 220px; height: 20px; text-align: center;'>" + state;
                    string tmpStr = string.Format("<input style=' float: right; right: 0px; margin-right: 10px; cursor: pointer;' type='button' id={0} class='btn-primary btn-mini' value='查看详情'  onclick=\"OnView('{0}',2)\" />", complaintdata[j].Id);
                    strHTML += tmpStr;
                    strHTML += "</li></ul></div>";
                }

            }
            #endregion
            var JsonData = new
            {
                html = strHTML,
                count = count
            };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取消息", "GetChatMessage")]
        public ActionResult GetChatMessage(string keyValue)
        {
            string _html = string.Empty; int count = 0;
            var datalist = bll.GetMsgList(keyValue).OrderBy(t => t.Date);

            if (datalist != null && datalist.Count() > 0)
            {
                count = datalist.Count();
                foreach (var a in datalist)
                {
                    var FromUser = new AccountBLL().GetEntity(a.FromUserId);
                    if (a.FromUserId == OperatorProvider.Provider.Current().UserId)
                    {
                        //right   
                        _html += " <div class='chat-message' >";
                        if (a.FromUserId == "System")
                        {

                            _html += "<img class='message-avatar message-avatar-right' src='/Content/images/on-line.png' /><div class='message message-right' style='background: #edfd00;'>";
                        }
                        else
                        {
                            _html += "<img class='message-avatar message-avatar-right' src='/Content/images/UserCard03.png' /><div class='message message-right'>";
                        }
                        _html += "<a class='message-author' > " + FromUser.Name + "</a><span class='message-date message-date-right'> <i class='fa fa-clock-o'></i> " + a.Date + " </span>";
                        _html += "<span class='message-content'>" + a.MsgContent + "</span></div>";
                        _html += "</div>";
                    }
                    else
                    {
                        //left
                        _html += "  <div class='chat-message'>";
                        _html += "<img class='message-avatar message-avatar-left' src='/Content/images/UserCard03.png' />";
                        _html += "<div class='message message-left'><a class='message-author' > " + FromUser.Name + "</a><span class='message-date message-date-left'> <i class='fa fa-clock-o'></i> " + a.Date + " </span>";
                        _html += "<span class='message-content'>" + a.MsgContent + "</span></div>";
                        _html += "</div>";
                    }
                }
            }

            var JsonData = new
            {
                html = _html,
                count = count
            };
            return Content(JsonData.ToJson());
        }
        #endregion

        #region
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存联系", "SaveForm")]
        public ActionResult SaveForm(string keyValue, LinkBillEntity linkBillEntity, string IMG)
        {
            List<Object> lst = IMG.ToObject<List<Object>>();
            List<AttachFileEntity> listFile = new List<AttachFileEntity>(); 
            string URL = Request.Url.ToString().Replace(Request.RawUrl, "/P");
            string SRC = URL.Substring(0, URL.IndexOf("/P"));
            string imgPath = "/Resource/LinkBillFile_" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";

            foreach (var item in lst)
            {
                var queryParam = item.ToString().ToJObject();
                string Name = queryParam["Name"].ToString(); 
                AttachFileEntity AttachFileEntity = new AttachFileEntity();
                AttachFileEntity.Create();
                AttachFileEntity.Category = 2;
                AttachFileEntity.Type = 21;
                AttachFileEntity.TypeName = "联系单附件";
                AttachFileEntity.FileName = Name;
                string FilePath = Server.MapPath(imgPath);
                AttachFileEntity.FileUrl = FilePath.Replace(HttpRuntime.AppDomainAppPath, SRC+"/") + Name;
                listFile.Add(AttachFileEntity);
            }
            try
            {
                 bll.SaveForm(keyValue, linkBillEntity, listFile);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        [HttpPost]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存消息", "SaveMSGForm")]
        public ActionResult SaveMSGForm(string keyValue, LinkChatMsgEntity linkChatMsgEntity)
        {
            try
            {
                // LinkChatMsgEntity linkChatMsgEntity = Obj.ToObject<LinkChatMsgEntity>();
                if (!string.IsNullOrEmpty(keyValue))
                {
                    linkChatMsgEntity.BillId = keyValue;
                    bll.SaveMSGForm(linkChatMsgEntity);
                    return Success("操作成功。");
                }
                else
                {
                    return Error("请先保存单据。");
                }

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }


        /// <summary>
        /// 转维修单
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="linkBillEntity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "转维修单", "CreateRepairForm")]
        public ActionResult CreateRepairForm(string keyValue, int Type, LinkBillEntity linkBillEntity)
        {
            try
            {
                return Success("操作成功", new { BillId = bll.CreateRepairForm(keyValue, Type, linkBillEntity) });
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        public ActionResult RemoveForm(string keyValue)
        {
            try
            {
                LinkBillEntity entity = bll.GetEntity(keyValue);
                if (entity.IsTurn == 1)
                {
                    var repairlist = new RepaireBLL().GetList().Where(t => t.EnabledMark == 1 && t.SourceId == entity.Id);
                    var complaintlist = new ComplaintsBLL().GetList().Where(t => t.EnabledMark == 1 && t.SourceId == entity.Id);
                    foreach (var a in repairlist)
                    {

                        new RepaireBLL().RemoveForm(a.Id);
                    }
                    foreach (var b in complaintlist)
                    {
                        b.EnabledMark = 0;
                        new ComplaintsBLL().RemoveForm(b.Id);
                    }
                }
                bll.RemoveForm(keyValue);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        /// <summary>
        /// 保存文件上传表单（新增、修改）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传文件", "UploadFile")]
        public ActionResult UploadFile()
        {

            hfc = System.Web.HttpContext.Current.Request.Files; 
            string imgPath = "/Resource/LinkBillFile_" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    string FilePath = Server.MapPath(imgPath);
                    if (!Directory.Exists(FilePath))
                    {
                        Directory.CreateDirectory(FilePath);
                    }
                    hfc[i].SaveAs(FilePath + hfc[i].FileName);
                }
            }
            return Success("操作成功。");

        }

       

        #endregion
    }
}
